package com.drojian.demo4.communication;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.drojian.demo.R;

public class HandlerThreadActivity extends AppCompatActivity {
    private TextView textView;
    private HandlerThread childHandlerThread;
    private Handler childHandler;
    private Handler mainHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.part4_activity_handler_thread);
        textView = findViewById(R.id.textView);
        mainHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if(msg.what == 0){
                    StringBuffer data = (StringBuffer) msg.obj;
                    textView.setText(data);
                    Toast.makeText(HandlerThreadActivity.this,"子线程执行完成",Toast.LENGTH_SHORT).show();
                }
            }
        };
        // 初始化HandlerThread
        childHandlerThread = new HandlerThread("DataLoader");
        childHandlerThread.start();
        childHandler = new Handler(childHandlerThread.getLooper());

    }

    public void startHandlerThread(View view) {
        StringBuffer data;
        try {
            data = loadData();
            Message msg = new Message();
            msg.what = 0;
            msg.obj = data;
            mainHandler.sendMessage(msg);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private StringBuffer loadData() throws InterruptedException {
        StringBuffer data = new StringBuffer();
        for (int i = 0; i < 100; i++) {
            data.append("我是第" + i + "条数据");
        }

        Thread.sleep(6000);
        return data;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (childHandlerThread != null) {
            childHandlerThread.quitSafely();
        }
    }
}